﻿using Core.FrameWork.Commons.Loging.Model;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Core.FrameWork.Commons.Loging
{
    public class EFCoreLogger : ILogger
    {
        private readonly string categoryName;

        public EFCoreLogger(string categoryName) => this.categoryName = categoryName;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            //EF Core执行SQL语句时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information
            if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command" && logLevel == LogLevel.Information)
            {
                var logContent = formatter(state, exception);

                ReqEfLogInfo reqEfLogInfo = new ReqEfLogInfo()
                {
                    Sql = logContent,
                    DateTime = DateTime.Now
                };

                LogLockHelper.OutSql2Log("SqlLog", "SqlLog" + DateTime.Now.ToString("yyyy-MM-dd"), new string[] {JsonConvert.SerializeObject(reqEfLogInfo) + "," }, false);


            }
        }

        public IDisposable BeginScope<TState>(TState state) => null;
    }
}
